package com.renwei.yunlong.fragment;

import android.annotation.SuppressLint;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;

import com.fingdo.statelayout.StateLayout;
import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.activity.news.ProblemInformationActivity;
import com.renwei.yunlong.activity.work.ComplaintsInformationActivity;
import com.renwei.yunlong.activity.work.SpareInformationActivity;
import com.renwei.yunlong.activity.work.WorkInformationActivity;
import com.renwei.yunlong.adapter.DealAllAdapter;
import com.renwei.yunlong.base.BaseRefreshFragment;
import com.renwei.yunlong.bean.UpcomingBean;
import com.renwei.yunlong.event.ComplainPageRefreshEvent;
import com.renwei.yunlong.event.ProblemPageStateRefreshEvent;
import com.renwei.yunlong.event.SparePageStateRefreshEvent;
import com.renwei.yunlong.event.WorkPageScreenEvent;
import com.renwei.yunlong.event.WorkPageStateRefreseEvent;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.zyf.fwms.commonlibrary.base.baseadapter.BaseRecyclerViewAdapter;

import java.util.HashMap;

import butterknife.Bind;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;


/**
 * 我的待办的全部--页面
 * <p>
 * Created by Administrator on 2017/9/6.
 */

@SuppressLint("ValidFragment")
public class DealAllFragment extends BaseRefreshFragment implements HttpTaskListener, View.OnClickListener, OnRefreshLoadmoreListener {

    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @Bind(R.id.state_layout)
    StateLayout stateLayout;
    @Bind(R.id.iv_top)
    ImageView ivTop;
    private int page = 1;
    private String content = "";
    private String startDate = "";
    private String endDate = "";
    private String companyCode = ""; //筛选企业
    private String contractId = "";  // 筛选项目
    private String upcoming;
    private int mPosition = -1;
    private DealAllAdapter adapter;

    public DealAllFragment(String upcoming) {
        this.upcoming = upcoming;
    }

    public DealAllFragment() {
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_me_upcoming;
    }

    @Override
    public void onPageCheck() {
        refreshLayout.autoRefresh();
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.setEnableScrollContentWhenLoaded(true);
        refreshLayout.setEnableScrollContentWhenRefreshed(true);
        refreshLayout.setOnRefreshLoadmoreListener(this);

        ivTop.setOnClickListener(this);
        adapter = new DealAllAdapter(getActivity());

        recyclerView.setAdapter(adapter);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            private int totalDy = 0;

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                totalDy -= dy;
                boolean isSignificantDelta = Math.abs(dy) > 0;
                if (isSignificantDelta) {
                    if (dy > 0) {
                        ivTop.setVisibility(View.GONE);
                    } else if (dy < 0) {
                        if (totalDy < -150)
                            ivTop.setVisibility(View.VISIBLE);
                        else
                            ivTop.setVisibility(View.GONE);
                    }
                }
            }
        });

        adapter.setOnItemClickLitener(new BaseRecyclerViewAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                mPosition = position;
                UpcomingBean.Rows bean = adapter.getData().get(position);
                if ("1".equals(bean.getKind())) {
                    WorkInformationActivity.OpenActivity(getContext(), bean.getRequestId() + "",
                            bean.getServerRequestId() + "", bean.getOutsourceFlag(), true);
                } else if ("2".equals(bean.getKind())) {
                    ProblemInformationActivity.OpenActivity(getContext(), bean.getRequestId() + "", bean.getMajorkey()
                            , bean.getOutsourceFlag(), true);
                } else if ("3".equals(bean.getKind())) {
                    ComplaintsInformationActivity.OpenActivity(getContext(), bean.getRequestId() + "", bean.getNewRequestId() + ""
                            , bean.getServerRequestId() + "", bean.getNewServerRequestId(), bean.getOutsourceFlag(),
                            bean.getMajorkey() + "", bean.getSendUserName());
                } else if ("4".equals(bean.getKind())) {
                    SpareInformationActivity.OpenActivity(getContext(), bean.getRequestId() + "",
                            bean.getOutsourceFlag(), bean.getMajorkey());
                }
            }
        });


    }

    // eventbus 状态回调
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onWorkStateRefresh(WorkPageStateRefreseEvent event) { // 状态刷新
        if (mPosition != -1) {
            if (!event.isRefresh && "1".equals(upcoming)) {
                adapter.removeData(mPosition);
            } else {
                adapter.getData().get(mPosition).setNowStat(event.nowState);
                adapter.notifyDataSetChanged();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onProblemStateRefresh(ProblemPageStateRefreshEvent event) {
        if (mPosition != -1) {
            if (!event.isRefresh && "1".equals(upcoming)) {
                adapter.removeData(mPosition);
            } else {
                adapter.getData().get(mPosition).setNowStat(event.nowState);
                adapter.notifyDataSetChanged();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onComplaintStateRefresh(ComplainPageRefreshEvent event) {
        refreshLayout.autoRefresh();
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onSpareStateRefresh(SparePageStateRefreshEvent event) {
        if (mPosition != -1) {
            if (!event.isRefresh && "1".equals(upcoming)) {
                adapter.removeData(mPosition);
            } else {
                adapter.getData().get(mPosition).setNowStat(event.nowState);
                adapter.notifyDataSetChanged();
            }
        }
    }


    /**
     * 筛选
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onScreen(WorkPageScreenEvent event) {
//        if (event.sort != 0) {
//            startDate = "";
//            endDate = "";
//            companyCode = "";
//            contractId = "";
//        } else {
            startDate = event.startDate;
            endDate = event.endDate;
            companyCode = event.companyCode;
            contractId = event.contractId;
//        }
        if (getUserVisibleHint()) {
            refreshLayout.setEnableLoadmore(true);
            refreshLayout.autoRefresh();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mPosition = -1;
    }

    public void initData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("kind", "0");
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        map.put("contractId", contractId);
        map.put("content", content);
        map.put("page", page + "");
        map.put("rows", 20 + "");
        if ("2".equals(companyType)) {
            map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
            map.put("ownerCode", companyCode);
        } else if ("1".equals(companyType)) {
            map.put("currentUserId", ownerBean.getRows().getEmployeeId());
            map.put("serviceProviderCode", companyCode);
        }
        ServiceRequestManager.getManager().getWorkList(getContext(), upcoming,
                JsonMapUtil.mapToJson(map), this);
    }

    @Override
    public void onSuccess(int requestId, String result) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
        UpcomingBean bean = new Gson().fromJson(result, UpcomingBean.class);
        if (bean.getMessage().getCode() == 200) {
            adapter.addAll(bean.getRows());
            if (bean.getRows().size() < 20) {
                refreshLayout.finishLoadmoreWithNoMoreData();
            }
            if (adapter.getData().size() == 0) {
                stateLayout.showEmptyView();
            } else {
                refreshLayout.resetNoMoreData();
                stateLayout.showContentView();
            }
        }
    }

    @Override
    public void onException(int requestId, String code) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
        stateLayout.showErrorView();
        page--;
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        page = 1;
        adapter.clean();
        initData();
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        page++;
        initData();
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_top:
                recyclerView.smoothScrollToPosition(0);
                break;
            default:
                break;
        }
    }
}
